package com.lzp.leetcode

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * @describe:字符串的最长子串
 * @Author: lixiaopeng
 * @Date: 4/15/21
 */
fun main() {
    val solution2 = solution2("ababced")
    println("$solution2")
}

/**
 * 这是我自己写的，leecode上的解法感觉有问题[solution]是leecode的解法，运行发信结果是6，但是实际上最大是5
 *
 * 解题思路是双指针
 */
fun solution2(s: String): Int {
    if (s.length == 0) {
        return 0
    }
    var result = ""
    var max = 0
    var left = 0

    for (right in s.indices) {
        println(right)
        if (result.contains(s[right])) {
            left++
            continue
        }
        result = s.substring(left, right + 1)
        max = Math.max(max, result.length)
        println("left = $left    right = $right    map = $result    max = $max")
    }
    return max
}

fun solution(s: String): Int {
    if (s.length == 0) {
        return 0
    }
    val map = mutableMapOf<Char, Int>()
    var max = 0
    var left = 0

    for (right in s.indices) {
        if (map.containsKey(s[right])) {
            val get = map.get(s.get(right)) ?: 0
            left = Math.max(left, get)
        }
        map[s[right]] = right
        max = Math.max(max, right - left + 1)

        println("left = $left    right = $right    map = ${map}    max = $max")
    }

    return max
}